package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chixing.commons.ServerResponse;
import com.chixing.commons.TokenUtil;
import com.chixing.mapper.CompanyDetailMapper;
import com.chixing.mapper.JobDetailMapper;
import com.chixing.pojo.*;
import com.chixing.mapper.MycollectsMapper;
import com.chixing.service.IJobDetailService;
import com.chixing.service.IMycollectsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 收藏表 服务实现类
 * </p>
 *
 * @author Jason Marslyon
 * @since 2022-10-04
 */
@Service
public class MycollectsServiceImpl  implements IMycollectsService {

    @Autowired
    private MycollectsMapper mycollectsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JobDetailMapper jobDetailMapper;

    @Autowired
    private CompanyDetailMapper companyDetailMapper;

    //    @Cacheable(value = "mycollectsList#2#m", key = "'add_collect'")
    @Override
    public ServerResponse saveCollection(Integer jobId, String token) {
        System.out.println("-----------------token"+token);
//        HashMap<Integer, Mycollects> mycollectsList = new HashMap<>();
        if (token!=null) {
            LoginPerson loginPerson = TokenUtil.parseToken(token);
            Integer perId = loginPerson.getPersonId();
            Mycollects mycollects = new Mycollects();
            mycollects.setMycollectStarttime(LocalDate.now());
            mycollects.setMycollectsVersion("0");
            mycollects.setJobId(jobId);
            mycollects.setMycollectState(0);
            mycollects.setPersonId(perId);
            QueryWrapper<Mycollects> wrapper = new QueryWrapper<>();
            wrapper.eq("person_id", perId);
            wrapper.eq("mycollect_state", 0);
            wrapper.eq("job_id", jobId);
            Mycollects mycollects1 = mycollectsMapper.selectOne(wrapper);
            if (mycollects1!=null) {
                System.out.println("////////////////////////////////////////////////");
                return ServerResponse.fail("插入职位失败，已经收藏了", null);
            } else{
                mycollectsMapper.insert(mycollects);
//        mycollectsList.put(perId,mycollects);
                String key="addcollect_personId_"+perId+"_jobId_"+jobId;
                redisTemplate.opsForValue().set(key,mycollects,2,TimeUnit.MINUTES);
                System.out.println("从数据库获取数据 ------------------------------------"+mycollects);

                return ServerResponse.success("插入收藏职位成功", mycollects);
            }

        }
        else{
            return ServerResponse.fail("插入职位失败，已经收藏了", null);
        }
    }

    @Override
    public ServerResponse getCollection(Integer jobId, String token) {
        System.out.println("********************************************************************************************");
        QueryWrapper<Mycollects> wrapper=new QueryWrapper<>();
        ValueOperations<String,Mycollects> valueOperations = redisTemplate.opsForValue();
        if (token!=null) {
            LoginPerson loginPerson = TokenUtil.parseToken(token);
            Integer perId=loginPerson.getPersonId();
            wrapper.eq("person_id", perId);
            wrapper.eq("mycollect_state",0);
            wrapper.eq("job_id",jobId);
            String key="addcollect_personId_"+perId+"_jobId_"+jobId;
            if (redisTemplate.hasKey(key)) {
                Mycollects mycollects =  valueOperations.get(key);
                System.out.println("从redis获取的mycollects-------------------------"+mycollects);
                return ServerResponse.success("redis查询成功，您已经收藏了", mycollects);
            }else {
                Mycollects mycollects = mycollectsMapper.selectOne(wrapper);
                if (mycollects != null){
                    redisTemplate.opsForValue().set(key,mycollects,2,TimeUnit.MINUTES);
                    return ServerResponse.success("数据库查询成功，您已经收藏了", mycollects);
                }
                else
                    return ServerResponse.fail("查询失败，您已经取消收藏或者未收藏", null);
            }
        }
        else
            return ServerResponse.fail("查询失败，您未登录或者未收藏",null);
    }

    @Override
    public ServerResponse updateIsDelCollect(Integer jobId, String token) {
        QueryWrapper<Mycollects> wrapper=new QueryWrapper<>();
        if (token!=null){
            Integer perId=TokenUtil.parseToken(token).getPersonId();
            wrapper.eq("person_id",perId);
            wrapper.eq("job_id",jobId);
            wrapper.eq("mycollect_state",0);
            String key="addcollect_personId_"+perId+"_jobId_"+jobId;
            if (redisTemplate.hasKey(key)){
                redisTemplate.delete(key);}
            Mycollects mycollects = mycollectsMapper.selectOne(wrapper);
//            UpdateWrapper<Mycollects> wrapper1=new UpdateWrapper<>();
//            wrapper1.set("mycollect_state",1);
//            wrapper1.set("mycollect_endTime",LocalDate.now());
//            mycollectsMapper.update(mycollects,wrapper1);
            mycollects.setMycollectState(1);
            mycollects.setMycollectEndtime(LocalDate.now());
            mycollectsMapper.update(mycollects,wrapper);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (redisTemplate.hasKey(key)){
                redisTemplate.delete(key);
            }
            return ServerResponse.success("取消收藏，将表中数据从0转为1",mycollects);
        }
        return ServerResponse.fail("取消收藏失败",null);
    }
    //分页
    @Override
    public ServerResponse getPage(Integer personId, Integer pageNum, String token) {
        PageHelper.startPage(pageNum,5);
        List<JobAndCompany> list =new ArrayList<>();
        QueryWrapper<Mycollects> wrapper =new QueryWrapper<>();
        wrapper.eq("person_id",personId);
        wrapper.eq("mycollect_state",0);
        wrapper.select("mycollect_id","job_id");    //select mycollect_id,job_id from table where person_id=proId and mycollect_state=0

        List<Mycollects> mycollectsList =mycollectsMapper.selectList(wrapper);
        PageInfo<Mycollects> pageInfo = new PageInfo<>(mycollectsList);
        for (Mycollects mycollects:mycollectsList) {
            QueryWrapper<JobDetail> jobQueryWrapper =new QueryWrapper<>();
            jobQueryWrapper.eq("job_id",mycollects.getJobId());
//            PageHelper.startPage(pageNum,5);
            JobDetail jobDetail =jobDetailMapper.selectOne(jobQueryWrapper);
            CompanyDetail companyDetail =companyDetailMapper.selectById(jobDetail.getCompanyId());
            JobAndCompany jobAndCompany =new JobAndCompany(jobDetail,companyDetail);
//            Map<String,Object> map =new HashMap<>();
//            map.put("mycollects",mycollects);
//            map.put("jobDetail",jobDetail);
//            map.put("companyDetail",companyDetail);
//            list.add(map);
            list.add(jobAndCompany);

        }
        if (list !=null){
//            PageHelper.startPage(pageNum,5);
            PageInfo<JobAndCompany> pageInfo1 = new PageInfo<>(list);
            pageInfo1.setPageNum(pageInfo.getPageNum());

            System.out.println(pageInfo1);
            return ServerResponse.success("查询收藏成功",pageInfo1);
        }
        return ServerResponse.fail("查询所有失败",null);
    }

    @Override
    public ServerResponse getTotal(Integer perId) {

        QueryWrapper<Mycollects> wrapper=new QueryWrapper<>();
        wrapper.eq("person_id",perId);
        wrapper.eq("mycollect_state",0);
        Long total = mycollectsMapper.selectCount(wrapper);

        return ServerResponse.success("查询成功",total);
    }


//    //分页
//    @Override
//    public ServerResponse getPage(Integer personId, Integer pageNum, String token) {
//        PageHelper.startPage(pageNum,5);
//        List<JobAndCompany> list =new ArrayList<>();
//        QueryWrapper<Mycollects> wrapper =new QueryWrapper<>();
//        wrapper.eq("person_id",personId);
//        wrapper.eq("mycollect_state",0);
//        wrapper.select("mycollect_id","job_id");    //select mycollect_id,job_id from table where person_id=proId and mycollect_state=0
//
//        List<Mycollects> mycollectsList =mycollectsMapper.selectList(wrapper);
//        PageInfo<Mycollects> pageInfo = new PageInfo<>(mycollectsList);
//        for (Mycollects mycollects:mycollectsList) {
//            QueryWrapper<JobDetail> jobQueryWrapper =new QueryWrapper<>();
//            jobQueryWrapper.eq("job_id",mycollects.getJobId());
////            PageHelper.startPage(pageNum,5);
//            JobDetail jobDetail =jobDetailMapper.selectOne(jobQueryWrapper);
//            CompanyDetail companyDetail =companyDetailMapper.selectById(jobDetail.getCompanyId());
//            JobAndCompany jobAndCompany =new JobAndCompany(jobDetail,companyDetail);
////            Map<String,Object> map =new HashMap<>();
////            map.put("mycollects",mycollects);
////            map.put("jobDetail",jobDetail);
////            map.put("companyDetail",companyDetail);
////            list.add(map);
//            list.add(jobAndCompany);
//
//        }
//        if (list !=null){
////            PageHelper.startPage(pageNum,5);
//            PageInfo<JobAndCompany> pageInfo1 = new PageInfo<>(list);
//            pageInfo1.setPageNum(pageInfo.getPageNum());
//
//            System.out.println(pageInfo1);
//            return ServerResponse.success("查询收藏成功",pageInfo1);
//        }
//        return ServerResponse.fail("查询所有失败",null);
//    }
}
